<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2018/6/27
 * Time: 21:11
 */

namespace App\Libs;


use App\Libs\Interfaces\BaiduTts;
use Illuminate\Support\Facades\Storage;

class BaiduTtsApi
{
    public function getAudioData($text)
    {
        $tts = new BaiduTts();

        return $tts->transition($text);
    }

    public function saveAudioFile($file_name,$file_data)
    {
        Storage::disk('audio')->put($file_name, $file_data);
    }

    public function getAudioSrc(string $template_id,array $template_params, $is_save=true)
    {
        $text_arr = $this->getTemplateTxt($template_id,$template_params);

        $file_name = $template_id.'_'.implode(',', $template_params).'.mp3';

        if(!Storage::disk('audio')->exists($file_name)){
            $data = $this->getAudioData($text_arr['text']);
            if($data){
                $this->saveAudioFile($file_name, $data);
            }else{
                return '';
            }

        }
        return [
            'rel_text' => $text_arr['rel_text'],
            'voice_src' => env('VOICE_BASESRC','').$file_name
        ];
    }

    public function getTemplateTxt(string $template_id,array $template_params)
    {
        $template_info = AudioTemplateConf::TEMPLATE[$template_id];
        $text = $template_info['text'];
        $rel_text = $template_info['rel_text'];

        foreach ($template_params as $key => $param){
            $text = str_replace('{$'.$key.'}',$param,$text);
            $rel_text = str_replace('{$'.$key.'}',$param,$rel_text);
        }

        return ['text' => $text, 'rel_text' => $rel_text];
    }
    /*
    public function getAudioPath(string $template_id,array $template_params)
    {

    }
    public function getTemplateTxt(string $template_id,array $template_params)
    {
        $template_info = AudioTemplateConf::TEMPLATE[$template_id];
        $txt = $template_info['text'];

        foreach ($template_params as $key => $param){
            $txt = str_replace('{$'.$key.'}',$param,$txt);
        }

        return $txt;
    }
    */
}